package com.xneure.database.sql.handler;

import com.xneure.database.metaobject.TableMetaObject;
import com.xneure.utils.ObjectUtil;

public class QueryHandler extends SqlHandler{
	private StringBuilder sql = new StringBuilder("SELECT ");
	private StringBuilder where = new StringBuilder(" WHERE ");
	private StringBuilder order = new StringBuilder(" ORDER BY ");

	@Override
	public void resetParam(){
		sql.setLength(7);
		where.setLength(7);
		order.setLength(10);
	}

	@Override
	public void addParam(String name,Object value){
		where.append(name).append(" = ").append(value);
	}

	public String getKey(Class<?> cls){
		return getMetaObject(cls).getIdKey().getName();
	}

	@Override
	public String getSql(){
		if(where.length() > 7){
			sql.append(where.toString());
		}
		if(order.length() > 10){
			order.setLength(order.length() - 1);
			sql.append(order.toString());
		}
		return sql.toString();
	}

	@Override
	public void addWhere(String where){
		if(ObjectUtil.isNotNull(where)){
			this.where.append(where);
		}
	}

	@Override
	public boolean isSupport(HandlerType hType,Class<?> cls){
		return HandlerType.QUERY == hType;
	}

	@Override
	public void build(Object obj){
		build(obj.getClass());
	}

	public void build(Class<?> cls){
		TableMetaObject metaObject = getMetaObject(cls);
		metaObject.getFields().forEach((k,f)-> {
			if(f.isIgnore() == false){
				if(null != f.getAnnotation() && f.getAnnotation().order().isEmpty() == false){
					order.append(f.getName()).append(" ").append(f.getAnnotation().order()).append(",");
				}
				sql.append(f.getName());
				sql.append(",");
			}
		});
		sql.setLength(sql.length() - 1);
		sql.append(" FROM ");
		sql.append(metaObject.getTableName());
	}
}
